package com.bc.plugin.doc.base.impl;

import com.bc.plugin.doc.base.IRequestHeaderHandler;
import com.power.common.util.StringUtil;
import com.power.doc.constants.DocAnnotationConstants;
import com.power.doc.model.ApiReqHeader;
import com.power.doc.utils.DocClassUtil;
import com.thoughtworks.qdox.model.JavaAnnotation;
import com.thoughtworks.qdox.model.JavaParameter;

import java.util.List;
import java.util.Map;

/**
 *
 * @author xhh 2019/11/21
 */
public class DefaultRequestHeaderHandler implements IRequestHeaderHandler {
    @Override
    public ApiReqHeader handle(JavaParameter javaParameter, Map<String, String> paramsComments) {
        List<JavaAnnotation> javaAnnotations = javaParameter.getAnnotations();
        String paramName = javaParameter.getName();
        for (JavaAnnotation annotation : javaAnnotations) {
            String annotationName = annotation.getType().getName();
            if (DocAnnotationConstants.REQUEST_HERDER.equals(annotationName)) {
                ApiReqHeader apiReqHeader = new ApiReqHeader();
                Map<String, Object> requestHeaderMap = annotation.getNamedParameterMap();
                if (requestHeaderMap.get(DocAnnotationConstants.VALUE_PROP) != null) {
                    apiReqHeader.setName(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.VALUE_PROP)));
                } else {
                    apiReqHeader.setName(paramName);
                }
                StringBuilder desc = new StringBuilder();
                String comments = paramsComments.get(paramName);
                desc.append(comments);

                if (requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP) != null) {
                    desc.append("(defaultValue: ")
                            .append(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP)))
                            .append(")");
                }
                apiReqHeader.setDesc(desc.toString());
                if (requestHeaderMap.get(DocAnnotationConstants.REQUIRED_PROP) != null) {
                    apiReqHeader.setRequired(!"false".equals(requestHeaderMap.get(DocAnnotationConstants.REQUIRED_PROP)));
                } else {
                    apiReqHeader.setRequired(true);
                }
                String typeName = javaParameter.getType().getValue().toLowerCase();
                apiReqHeader.setType(DocClassUtil.processTypeNameForParams(typeName));
                return apiReqHeader;
            }
        }
        return null;
    }
}
